package com.flca.frw.zk.validate;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zul.Constraint;

public class ValidateString implements Constraint {

	private boolean req;
	private Integer minLength;
	private Integer maxLength;
	
	public ValidateString(Integer aMinLength, Integer aMaxLength, boolean aRequired) 
	{
		super();
		
		this.req = aRequired;
		
		if (aMinLength != null) {
				this.minLength = ((Integer) aMinLength).intValue();
		} 

		if (aMaxLength != null) {
				this.maxLength = ((Integer) aMaxLength).intValue();
		} 
	}

	public void validate(Component aComp, Object aValue) 	throws WrongValueException 
	{
		if (isEmpty(aValue) && req) {
			String msg = "Dit veld is verplicht"; 
			throw new WrongValueException(aComp, msg);
		} 
		
		else if (aValue != null && aValue instanceof String) {
			String str = (String) aValue;

			if (minLength != null) {
				if (str.length() < minLength.intValue()) {
					String msg = "Minimum lengte = " + minLength; 
					throw new WrongValueException(aComp, msg);
				}
			}

			if (maxLength != null) {
				if (str.length() > maxLength.intValue()) {
					String msg = "Maximum lengte = " + maxLength; 
					throw new WrongValueException(aComp, msg);
				}
			}
		} 
	}

	private boolean isEmpty(Object aValue) 
	{
		if (aValue == null) {
			return true;
		} else {
			return aValue.toString().length() == 0;
		}
	}
}
